import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_native_image/flutter_native_image.dart';
//import 'package:flutter_native_image/flutter_native_image.dart';
import 'package:image_picker/image_picker.dart';
import 'package:magic_car/jiance/papularInspects.dart';
import 'package:magic_car/jiance/papularinspect.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:toast/toast.dart';
//import 'package:amap_location/amap_location.dart';
//import 'package:amap_location_fluttify/amap_location_fluttify.dart';
import 'dart:io';
//import 'package:amap_location/amap_location.dart';
import 'package:permission_handler/permission_handler.dart';
//import 'package:amap_search_fluttify/amap_search_fluttify.dart';

class StartPicPage extends StatefulWidget {
  final String param;
  StartPicPage(this.param);

  @override
  _MyHomePageState createState() => new _MyHomePageState(this.param);
}

class _MyHomePageState extends State<StartPicPage> {
  List formList;
  final String param;
  bool select = false;
  String itemid;
  String img_url = '';
  String attachment = '';
  //final _amapLocation = AMapLocation();
  var _result = '';
  // Location location = new Location();
  bool _serviceEnabled;
  // PermissionStatus _permissionGranted;
  // LocationData _locationData;

  String address = "";

  String _platformVersion = 'Unknown';

  _MyHomePageState(this.param);
  initState() {
    super.initState();
    formList = [
      {
        "title": '客户姓名',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '车牌号',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '车牌号',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '车牌号',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
    ];
    startLcoations();
   // getLocationInfo();
  }

//   void getLocationInfo() async {
//     Map permissions = await PermissionHandler()
//         .requestPermissions([PermissionGroup.location]);
// // 申请结果
//     PermissionStatus permission = await PermissionHandler()
//         .checkPermissionStatus(PermissionGroup.location);
//     if (permission == PermissionStatus.granted) {
// //_getLocation();
//       await AMapLocationClient.startup(new AMapLocationOption(
//           desiredAccuracy: CLLocationAccuracy.kCLLocationAccuracyBest));
// //获取地理位置（直接定位）
//       var result = await AMapLocationClient.getLocation(true);
//       if (result != null) {
//         postBaiduLoaction(
//             result.latitude.toString(), result.longitude.toString());
//       }
//     } else {
// //bool isOpened = await PermissionHandler().openAppSettings();//打开应用设置
//     }
//   }

  startLocation() async {
    // _serviceEnabled = await location.serviceEnabled();
    // if (!_serviceEnabled) {
    //   _serviceEnabled = await location.requestService();
    //   if (!_serviceEnabled) {
    //     return;
    //   }
    // }

    // _permissionGranted = await location.hasPermission();
    // if (_permissionGranted == PermissionStatus.DENIED) {
    //   _permissionGranted = await location.requestPermission();
    //   if (_permissionGranted != PermissionStatus.GRANTED) {
    //     return;
    //   }
    // }
    // _locationData = await location.getLocation();

    // print(_locationData.latitude);
    // print(_locationData.longitude);
    // Map<String, String> map = new Map();
    // map = {
    //   'lat': _locationData.latitude.toString(),
    //   'lng': _locationData.longitude.toString()
    // };
    // HttpHelper.PostLocation((data) async {
    //   //loadpage.close();
    //   if (data != null) {
    //     print(data);
    //     if (data['status'].toString() == "0") {
    //       print(data['result']['formatted_address']);
    //       setState(() {
    //         address = data['result']['formatted_address'];
    //       });
    //     } else {
    //       Toast.show('获取位置信息失败', context);
    //     }
    //   }
    // }, params: map);
  }

  startLcoations() async{
  //   print('开始定位');
  //    AMapLocationClient.setApiKey("a2e9cf9d406e395b088803572c837e94");
  //   Map<PermissionGroup, PermissionStatus> permissions =
  //     await PermissionHandler().requestPermissions([PermissionGroup.location]);
  //   // 申请结果
  //   PermissionStatus permission = await PermissionHandler()
  //       .checkPermissionStatus(PermissionGroup.location);
  //       print('授权结果');
  //   if (permission == PermissionStatus.granted) {    
  //     print('授权成功');
  //    AMapLocationClient.startup(new AMapLocationOption(
  //         desiredAccuracy: CLLocationAccuracy.kCLLocationAccuracyHundredMeters));
  //    AMapLocationClient.startLocation();
  //   var geting = await AMapLocationClient.getLocation(true);
  //   LatLng lat = new LatLng(geting.latitude.toDouble(), geting.longitude.toDouble());
  //   ReGeocode reGeocodeList = await AmapSearch.searchReGeocode(
  //     lat,
  //   );
  //   print(await reGeocodeList.toFutureString());
  //  String addresstemp = await reGeocodeList.formatAddress;
  //    setState(() {
  //           address = addresstemp;
  //         });
    
   // postBaiduLoaction(geting.latitude.toString(), geting.longitude.toString());
    //print(geting.longitude);
    //print(geting);
    //Toast.show('位置信息'+geting.longitude.toString(), context);
      //启动监听位置改变
      
      
    // } else {
    //  print('授权失败');
    // }
    // AMapLocationClient.setApiKey("525046dad090259a9fe5fd02a417b04c");
    //  // 申请权限
    // Map<PermissionGroup, PermissionStatus> permissions =
    //     await PermissionHandler()
    //         .requestPermissions([PermissionGroup.location]);
    // // 申请结果
    // PermissionStatus permission = await PermissionHandler()
    //     .checkPermissionStatus(PermissionGroup.location);
    //     print('授权结果');
    // if (permission == PermissionStatus.granted) {    
    //   // print('授权成功');
    //   //   //授权成功--》
    //   // // 启动系统所需选项
    //   // // AMapLocationClient.startup(new AMapLocationOption(
    //   // //     desiredAccuracy: CLLocationAccuracy.kCLLocationAccuracyHundredMeters));
     
    //   //   //获取当前位置
    //   //   //启动监听位置改变
    //   // AMapLocationClient.startLocation();
    //   // var geting = await AMapLocationClient.getLocation(true);
    //   // print('结果');
    //   // print( geting.longitude);
    //   // postBaiduLoaction(geting.latitude, geting.longitude);
     
    //   // //定位改变监听
    //   // AMapLocationClient.onLocationUpate.listen((AMapLocation loc){
    //   //   postBaiduLoaction(geting.latitude, geting.longitude);

    //   //   if(!mounted)return;
        
    //   // });

    //   AMapLocationClient.startup(new AMapLocationOption(
    //     desiredAccuracy: CLLocationAccuracy.kCLLocationAccuracyHundredMeters));

    // //监听坐标实时变换
    // AMapLocationClient.onLocationUpate.listen((AMapLocation loc) {
    //   if (!mounted) return;
    //   print(loc);
    //  postBaiduLoaction(loc.latitude, loc.longitude);
    // });

    // AMapLocationClient.startLocation();
      
     
    // } else {
    //   Toast.show('请打开定位权限，获取位置', context);
     
    // }
  }

  postBaiduLoaction(lat, lng) {
    Map<String, String> map = new Map();
    map = {'lat': lat, 'lng': lng};
    HttpHelper.PostLocation((data) async {
      //loadpage.close();
      if (data != null) {
        print(data);
        if (data['status'].toString() == "0") {
          print(data['result']['formatted_address']);
          setState(() {
            address = data['result']['formatted_address'];
          });
        } else {
          Toast.show('获取位置信息失败', context);
        }
      }
    }, params: map);
  }
  //  void _checkPersmission() async{
  //   bool hasPermission = await SimplePermissions.checkPermission(Permission.WhenInUseLocation);
  //   if(!hasPermission){
  //     bool requestPermissionResult = await SimplePermissions.requestPermission(Permission.WhenInUseLocation);
  //     if(!requestPermissionResult){
  //       Alert.alert(context,title: "申请定位权限失败");
  //       return;
  //     }
  //   }
  //初始化定位监听，
  // void startLocation() async {

  //  _amapLocation.init();

  //   final options = LocationClientOptions(
  //     isOnceLocation: false,
  //     locatingWithReGeocode: true,
  //   );

  //   if (await Permissions().requestPermission()) {
  //     _amapLocation.startLocate(options).listen((_) => setState(() {
  //           _result =
  //               '坐标：${_.longitude}，${_.latitude} @ ${DateTime.now().hour}:${DateTime.now().minute}:${DateTime.now().second}';
  //         }));
  //   } else {
  //     setState(() {
  //       _result = "无定位权限";
  //     });
  //   }

  // print('开始定位');
  // AMapLocationClient.startup(new AMapLocationOption(
  //     desiredAccuracy: CLLocationAccuracy.kCLLocationAccuracyHundredMeters));

  // //监听坐标实时变换
  // AMapLocationClient.onLocationUpate.listen((AMapLocation loc) {
  //   if (!mounted) return;
  //   print(loc.latitude);
  //   // setState(() {
  //   //   lat = loc.latitude;
  //   //   long = loc.longitude;
  //   // });
  // });

  // AMapLocationClient.startLocation();
  //}

  photo(item) async {
    var image = await ImagePicker.pickImage(source: ImageSource.camera);
    if (image == null) return;
    // File _files = await FlutterNativeImage.compressImage(image.path);
    File _files = image;
    Map<String, String> map = new Map();

    HttpHelper.upLoadImage(_files, (data) {
      print('data');
      if (data.containsKey('code')) {
        Toast.show(data['msg'], context);
      } else {
        // List tempimg1 =
        //     item.containsKey("urlArr1") ? item["urlArr1"] : new List();
        // List tempimg = new List();
        // tempimg.add(data["filename"]);
        // tempimg.add(data["url"]);
        // tempimg1.add(tempimg);
        // setState(() {
        //   item["urlArr1"] = tempimg1;
        // });
      }
    }, params: map);
  }

  //选择图片方式
  Future getImage(i) async {
    getimgs(0, i);
    // showDialog(
    //     context: context,
    //     builder: (BuildContext context) {
    //       return new SimpleDialog(
    //         title: new Text('选择'),
    //         children: <Widget>[
    //           new SimpleDialogOption(
    //             child: new Text('相机'),
    //             onPressed: () {
    //               Navigator.pop(context);
    //               getimgs(0, i);
    //             },
    //           ),
    //           new SimpleDialogOption(
    //             child: new Text('相册'),
    //             onPressed: () {
    //               Navigator.pop(context);
    //               getimgs(1, i);
    //             },
    //           )
    //         ],
    //       );
    //     });
    // var image = await ImagePicker.pickImage(source: ImageSource.gallery);
    // //_upLoadImage(image);//上传图片
    // setState(() {
    //   _image = image;
    // });
  }

  //选择图片
  getimgs(type, index) async {
    var image;
    if (type == 1) {
      image = await ImagePicker.pickImage(source: ImageSource.gallery);
    } else {
      image = await ImagePicker.pickImage(source: ImageSource.camera);
    }
    if (image == null) return;
    // LoadingPage loadpage = new LoadingPage(context);
    // loadpage.show();
    File _files = await FlutterNativeImage.compressImage(image.path);

    Map<String, String> map = new Map();

    HttpHelper.upLoadImage(_files, (data) {
      //loadpage.close();
      print('data');
      if (data.containsKey('code')) {
        Toast.show(data['msg'], context);
      } else {
        setState(() {
          img_url = data['url'];
          attachment = data['attachment'];
        });
      }
    }, params: map);
  }

  Widget buildcontent() {
    List<Widget> tiles = [];
    Widget content;
    tiles.add(new Container(
        child: new Padding(
            padding: new EdgeInsets.fromLTRB(0, 15, 0, 0),
            child: new GestureDetector(
              onTap: () {
                getImage(0);
              },
              child:img_url==""?Image.asset("resource/images/user/upimg.png"):CachedNetworkImage(imageUrl: img_url,width: 300,
                height: 200,)
              //  FadeInImage.assetNetwork(
              //   placeholder: "resource/images/user/upimg.png",
              //   image: img_url,
              //   width: 300,
              //   height: 200,
              //   //fit: BoxFit.contain,
              // ),
            ))));
    tiles.add(address == ""
        ? new Container(height: 0)
        : Container(
            child: new Padding(
                padding: new EdgeInsets.fromLTRB(0, 15, 0, 0),
                child: new GestureDetector(
                    onTap: () {
                      getImage(0);
                    },
                    child: 
                    new Padding(
                padding: new EdgeInsets.fromLTRB(15, 0, 15, 0),
                child:
                    new Text(address,style: TextStyle(fontSize:15),))))));

    tiles.add(Padding(
      padding: new EdgeInsets.fromLTRB(20, 20, 20, 0),
      child: Container(
        width: double.infinity,
        color: Color.fromRGBO(27, 182, 251, 1),
        child: new FlatButton(
            onPressed: () {
              next();
            },
            child: new Text(
              '下一步',
              style: TextStyle(color: Colors.white),
            )),
      ),
    ));
    content = new Column(
        children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
        //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
        );
    return content;
  }

  next() {
    if (img_url == '') {
      Toast.show('请上传人车合照', context);
      return;
    } else {
      Map param = {
        "id": '9999',
        "post_id": '4000',
        "name": "人车合照",
        "status": 2,
        "stat": 1,
        "created_at": "2019-03-07 19:40:57",
        "updated_at": "2019-03-07 19:40:57",
        "ismust": 1,
        "url": img_url,
        "url2": attachment,
        "item": '',
      };
      // Map param = {'url':img_url,'attachment':attachment};
      Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
       // return new Papularinspects(this.param, 1, param);
      }));
    }
  }

  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: new Text('人车合照'),
          backgroundColor: Colors.white,
          iconTheme: new IconThemeData(color: Colors.black),
          elevation: 0,
          // backgroundColor: Color.fromRGBO(255, 204, 48, 1),
        ),
        body: new Center(
            child: Container(
          decoration: new BoxDecoration(
            color: Color.fromRGBO(238, 238, 238, 1),
          ),
          child: Padding(
              padding: new EdgeInsets.fromLTRB(0, 15, 0, 0),
              child: new ListView(
                children: <Widget>[buildcontent()],
              )),
        )));
  }

  Future<bool> willpop() {
    _showDialog();
    return Future.value(false);
  }

  _showDialog() {
    showDialog<Null>(
      context: this.context,
      builder: (BuildContext context) {
        return new AlertDialog(
            title: Text('提示!'),
            content: new Text('此项是否已经检测完毕?'),
            actions: <Widget>[
              new FlatButton(
                  onPressed: () {
                    Navigator.of(this.context).pop();
                    // Navigator.pop(context);
                  },
                  child: new Text('否，继续检测',
                      style: new TextStyle(color: Colors.red))),
              new FlatButton(
                  onPressed: () {
                    Navigator.of(this.context).pop();
                    //sleep(Duration(seconds: 1));
                    Navigator.pop(context);
                  },
                  child: new Text(
                    '是',
                    style: new TextStyle(color: Colors.black),
                  ))
            ]);
      },
    );
  }
}

class NinePicture<T> extends PopupRoute<T> {
  final String barrierLabel;
  final List picList;
  final int index;
  int startX;
  int endX;

  NinePicture(this.picList, this.index, {this.barrierLabel});

  @override
  Duration get transitionDuration => Duration(milliseconds: 2000);

  @override
  @override
  Color get barrierColor => Colors.black54;

  @override
  bool get barrierDismissible => true;

  AnimationController _animationController;

  @override
  AnimationController createAnimationController() {
    assert(_animationController == null);
    _animationController =
        BottomSheet.createAnimationController(navigator.overlay);
    return _animationController;
  }

  @override
  Widget buildPage(BuildContext context, Animation<double> animation,
      Animation<double> secondaryAnimation) {
    return MediaQuery.removePadding(
      removeTop: true,
      context: context,
      child: GestureDetector(
        child: AnimatedBuilder(
          animation: animation,
          builder: (BuildContext context, Widget child) => GestureDetector(
            onTap: () {
              Navigator.pop(context);
            },
            child: _PictureWidget(picList, index),
          ),
        ),
      ),
    );
  }
}

class _PictureWidget extends StatefulWidget {
  final List picList;
  final int index;

  _PictureWidget(this.picList, this.index);

  @override
  State createState() {
    return _PictureWidgetState();
  }
}

class _PictureWidgetState extends State<_PictureWidget> {
  int startX = 0;
  int endX = 0;
  int index = 0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    index = widget.index;
  }

  @override
  Widget build(BuildContext context) {
    return new Material(
      color: Colors.transparent,
      child: new Container(
        width: double.infinity,
        child: Stack(
          children: <Widget>[
            GestureDetector(
              child: Center(
                child: CachedNetworkImage(
                  imageUrl: widget.picList[index][1],
                  fit: BoxFit.cover,
                ),
              ),
              onHorizontalDragDown: (detail) {
                startX = detail.globalPosition.dx.toInt();
              },
              onHorizontalDragUpdate: (detail) {
                endX = detail.globalPosition.dx.toInt();
              },
              onHorizontalDragEnd: (detail) {
                _getIndex(endX - startX);
                setState(() {});
              },
              onHorizontalDragCancel: () {},
            ),
            Align(
              alignment: Alignment.bottomCenter,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: List.generate(
                  widget.picList.length,
                  (i) => GestureDetector(
                    child: CircleAvatar(
                      foregroundColor: Theme.of(context).primaryColor,
                      radius: 8.0,
                      backgroundColor: index == i
                          ? Theme.of(context).primaryColor
                          : Colors.white,
                    ),
                    onTap: () {
                      setState(() {
                        startX = endX = 0;
                        index = i;
                      });
                    },
                  ),
                ).toList(),
              ),
            )
          ],
        ),
        alignment: Alignment.center,
      ),
    );
  }

  void _getIndex(int delta) {
    if (delta > 50) {
      setState(() {
        index--;
        index = index.clamp(0, widget.picList.length - 1);
      });
    } else if (delta < 50) {
      setState(() {
        index++;
        index = index.clamp(0, widget.picList.length - 1);
      });
    }
  }
}
